import { singleFunction } from '@/utils/single';

const defaultConfig = {
  duration: 3,
  getContainer: () => document.body,
  maxCount: 3,
  rtl: false,
  prefixCls: 'ant-message',
  top: '8px',
};

const setupMessage = (message, config) => {
  message.config({ ...defaultConfig, ...config });
};

// 单例模式
export const useSingleMessage = (message, config) => setupMessage(message, { ...config, maxCount: 1 });

// 自定义配置
export const useCustomMessage = (message, config) => setupMessage(message, config);

// 队列模式
export const useQueueMessage = singleFunction((message, config) => {
  setupMessage(message, { ...config, duration: 2, maxCount: 0 });
  let messageInstance = null;
  const queueMessages = [];
  const messageTypes = ['info', 'success', 'warn', 'warning', 'error', 'loading'];

  const nextMessage = function () {
    messageInstance = null;
    const nextMessage = queueMessages.shift();
    nextMessage && nextMessage();
  };

  const execute = (type) => {
    const instance = message[type];
    message[type] = function (...args) {
      if (messageInstance !== null) {
        return new Promise((resolve) => queueMessages.push(() => resolve(message[type](...args))));
      }
      messageInstance = instance.apply(this, args);
      messageInstance.then(() => nextMessage());
      return messageInstance;
    };
  };

  messageTypes.forEach(execute);
});
